import { Col, Input, Modal, Radio, Row, Checkbox, Tooltip, Divider, message } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import { useEffect, useState } from 'react';
import _ from 'lodash'
import { useDebounce } from '@/utils/utils'
import { insertRelation, searchObjectName, showRelation } from '@/services/relate'
import styles from './index.less'

const RelateModal = (props) => {
  const { visible, closeVisible, id } = props;
  const [relateVal, setRelateVal] = useState('1');
  const [ relateRightVal, setRelateRightVal ] = useState('')
  const [okrCacheOptions, setOkrCacheOptions] = useState([])
  const [okrOptions, setOkrOptions] = useState([])
  const [selectListRight, setSelectListRight] = useState([]); //右侧
  const [selectRightCache, setSelectRightCache] = useState([]);
  const [disList, setDisList] = useState([]); //禁选
  const [checkList, setCheckList] = useState([])
  const [leftList, setLeftList] = useState([]);


  useEffect(() => {
    showRelation({objectId: id}).then((res)=>{
      if(res.code == 200) {
        const list = res.data.length > 0 ? res.data.map((item)=>{
          return {
            id: item.targetId,
            name: item.targetName || '--',
            mode: item.relation_type || '1',
            type: item.target_type || '0', //代表O或者KR
          }
        }) : [];
        setSelectListRight(_.uniqBy(list, 'id'));
        setSelectRightCache(_.uniqBy(list, 'id'))
      }
    })
  }, []);

  const handleOk = () => {
    const params = selectListRight.map((item, index)=>{
      return {
        startId: id,
        targetId: item.id,
        relationType: item.mode,
        startType: '0',
        targetType: item.type,
      }
    })
    insertRelation(params).then((res)=>{
      if(res.code == 200) {
        message.success('保存成功')
        closeVisible()
      }
    })
  };
  const onChange = (e) => {
    setRelateVal(e.target.value);
    const val = e.target.value;
    const disableList = leftList.length > 0 ? leftList.filter(item => item.mode != val).map(item => item.id) : [];
    setDisList(disableList.length > 0 ? disableList : [])
  };
  const onChangeRadio = (e) => {
    setRelateRightVal(e.target.value)
  }
  const handleCheckout = (checkIds) => {
    setCheckList(checkIds)
    const selectList = checkIds.length > 0 ? checkIds.map((item, index)=>{
      const currItem = okrCacheOptions.filter(val => val.id === item)[0]
      const objArr = leftList.length > 0 ? leftList.filter(itemVal => itemVal.id === item) : [];
      const obj = objArr.length > 0 ? objArr[0] : Object.assign({}, currItem, { mode: relateVal })
      return obj
    }) : [];
    setLeftList(selectList)
    const disableList = selectList.length > 0 ? selectList.filter(item => item.mode != relateVal).map(item => item.id) : [];
    setDisList(disableList.length > 0 ? disableList : [])
    setSelectListRight(_.uniqBy(selectList.concat(selectRightCache), 'id'))
  }
  const deleteRelate = (item) => {
    let arr = checkList.filter(val => val !== item.id);
    let lists = selectListRight.filter(val => val.id !== item.id); // 左侧选中的，需删除
    let cacheRight =selectRightCache.filter(val => val.id !== item.id); // 右侧缓存的list 需要删除
    setSelectListRight(lists)
    setCheckList(arr);
    setSelectRightCache(cacheRight)
  }
  const searchOkr = (e) => {
    const val = e.target.value;
    if(val) { searchDebounce(val) }
  }
  const searchDebounce = useDebounce((val)=>{
    searchObjectName({name: val}).then((res)=>{
      if(res.code == 200){
        setOkrCacheOptions(res?.data || [])
        setOkrOptions(res?.data || [])
      }
    })
  }, 1000)

  return (
    <>
      <Modal
        title="关联"
        width={800}
        visible={visible}
        onOk={handleOk}
        onCancel={closeVisible}
      >
        <Row gutter={50} className={styles.relateWrap}>
          <Col span={12} style={{ borderRight: '1px solid #cccccc' }}>
            <Input.Search placeholder="搜索部门或者OKR" onChange={searchOkr}></Input.Search>
            <Radio.Group onChange={onChange} value={relateVal}>
              <Radio value={'1'}>支撑</Radio>
              <Radio value={'2'}>协作</Radio>
              <Radio value={'3'}>依赖</Radio>
            </Radio.Group>
            <Divider />
            {okrOptions.length > 0 && <Row gutter={20} style={{ fontWeight: 500, color: '#342f6b' }}>
                    <Col span={18} style={{ paddingLeft: '20px' }}>名称</Col>
                    <Col span={4} style={{ textAlign:'center' }}>类型</Col>
                  </Row>}
            <Divider />
            <Checkbox.Group onChange={handleCheckout} value={checkList} >
              {okrOptions.length > 0 && okrOptions.map((item, index)=>(<Checkbox key={item.id} disabled={disList.includes(item.id)} value={item.id}>
                <Tooltip placement="topLeft" title={item.name}>
                  <Row gutter={20} style={{ margin: '5px 0' }}>
                    <Col span={18} className={styles.okr_name_css}>{item.name}</Col>
                    <Col span={4} style={{ color: '#342f6b',textAlign:'center' }}>{item.type == '0' ? 'O' : 'KR'}</Col>
                  </Row>
                </Tooltip>
              </Checkbox>))}             
            </Checkbox.Group>
          </Col>
          <Col span={12}>
          <Radio.Group onChange={onChangeRadio} value={relateRightVal}>
              <Radio value={''}>全部</Radio>
              <Radio value={'1'}>支撑</Radio>
              <Radio value={'2'}>协作</Radio>
              <Radio value={'3'}>依赖</Radio>
            </Radio.Group>
            <Divider />
            <ul style={{ padding: '10px' }}>
            {selectListRight.length > 0 && !!relateRightVal && selectListRight.filter(val => val.mode == relateRightVal).map((item, index)=>(<li className={styles.li_right_wrap} key={index} value={item.id}>
                <Tooltip placement="topLeft" title={item.name}>
                  <span className={styles.right_text}>{item.name}</span>
                </Tooltip>
                <span className={styles.deleteIcon}><DeleteOutlined onClick={()=>deleteRelate(item)} /></span>
              </li>))}   
              {selectListRight.length > 0 && !relateRightVal && selectListRight.map((item, index)=>(<li className={styles.li_right_wrap} key={index} value={item.id}>
                <Tooltip placement="topLeft" title={item.name}>
                   <span className={styles.right_text}>{item.name}</span>
                </Tooltip>
                <span className={styles.deleteIcon}><DeleteOutlined onClick={()=>deleteRelate(item)} /></span>
              </li>))}   
            </ul>
          </Col>
        </Row>
      </Modal>
    </>
  );
};

export default RelateModal;
